import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:yyshort/common/apis/user_api.dart';
import 'package:yyshort/common/langs/translation_service.dart';
import 'package:yyshort/common/model/useInfo_model.dart';
import 'package:yyshort/common/routers/pages.dart';
import 'package:yyshort/common/store/store.dart';
import 'package:yyshort/common/style/style.dart';
import 'package:yyshort/common/utils/device_info_util.dart';
import 'package:yyshort/common/utils/json_storage_util.dart';
import 'package:yyshort/common/utils/network_provider.dart';
import 'package:yyshort/common/utils/utils.dart';
import 'package:yyshort/global.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yyshort/pages/ali_player/short_video/SharedDataController.dart';
import 'package:yyshort/common/utils/appsflyer_set_DMA_compliance.dart';
import 'package:yyshort/common/utils/appsflyer_ascribe.dart'; // 新增归因

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await UserInfo().loadFromLocal();
  await Global.init();
  await Hive.initFlutter();
  await JsonStorageUtil.init();

  Map<String, String> info = await DeviceInfoService().getDeviceInfo();
  print(
    '品牌: ${info['brand']}, 型号: ${info['model']}, 设备ID: ${info['deviceId']}',
  );
  AppLifecycleManager().init();

  runApp(MyApp());

  // 在界面绘制后异步执行AppsFlyer初始化（不阻塞UI）
  WidgetsBinding.instance.addPostFrameCallback((_) {
    // 初始化 AppsFlyer SDK
    initAppsflyerAscribe();
  });

  debugPrint('应用启动完成');
}

Future<void> initAppsflyerAscribe() async {
  // 1. 初始化AppsFlyer SDK实例
  await AppsflyerAscribe().initialize();
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: Size(375, 812),
      builder: (context, child) => RefreshConfiguration(
        headerBuilder: () => const ClassicHeader(),
        footerBuilder: () => const ClassicFooter(),
        hideFooterWhenNotFull: true,
        headerTriggerDistance: 80,
        maxOverScrollExtent: 100,
        footerTriggerDistance: 150,
        child: GetMaterialApp(
          navigatorKey: navigatorKey,
          // title: 'News',
          theme: AppTheme.light,
          debugShowCheckedModeBanner: false,
          initialRoute: AppPages.INITIAL,
          getPages: AppPages.routes,
          builder: EasyLoading.init(),
          translations: TranslationService(),
          navigatorObservers: [AppPages.observer],
          localizationsDelegates: [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          locale: ConfigStore.to.locale,
          fallbackLocale: Locale('en'),
          enableLog: true,
          logWriterCallback: Logger.write,
        ),
      ),
    );
  }
}

class AppLifecycleManager with WidgetsBindingObserver {
  static final AppLifecycleManager _instance = AppLifecycleManager._internal();
  factory AppLifecycleManager() => _instance;
  AppLifecycleManager._internal();

  void init() {
    WidgetsBinding.instance.addObserver(this);
  }

  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        debugPrint('应用回到前台');
        UserAPI.add_user_active_log();
        break;
      case AppLifecycleState.inactive:
        debugPrint('应用处于非活动状态');
        eventBus.fire(StopPlayerEvent());
        break;
      case AppLifecycleState.paused:
        debugPrint('应用进入后台');
        eventBus.fire(StopPlayerEvent());
        break;
      case AppLifecycleState.detached:
        debugPrint('应用即将退出');
        await JsonStorageUtil.deleteJson(key: 'for_you_videos');
        eventBus.fire(StopPlayerEvent());
        break;
      case AppLifecycleState.hidden:
        debugPrint('应用处于隐藏状态');
        eventBus.fire(StopPlayerEvent());
        break;
    }
  }
}
